import { config } from '../config';
import { get, HttpError, putJson } from '../utils/fetch';

export interface CatalogItem {
  id: string;
  name: string;
  description?: string;
  price: number;
  stock: number;
  pictureUrl?: string;
  category?: string;
}

export interface BasketItem {
  productId: string;
  productName: string;
  unitPrice: number;
  quantity: number;
}

export interface BasketResponse {
  items: BasketItem[];
  total: number;
  updatedAt: string;
}

export async function fetchCatalogItems(): Promise<CatalogItem[]> {
  if (!config.BFF_BASE_URL) {
    throw new Error('BFF base url is not configured');
  }

  return get<CatalogItem[]>('/bff/catalog/items', {
    baseUrl: config.BFF_BASE_URL,
    credentials: 'include',
  });
}

export async function fetchCatalogItem(id: string): Promise<CatalogItem | null> {
  const items = await fetchCatalogItems();
  return items.find((item) => String(item.id) === id) ?? null;
}

export async function fetchBasket(): Promise<BasketResponse> {
  if (!config.BFF_BASE_URL) {
    throw new Error('BFF base url is not configured');
  }

  try {
    return await get<BasketResponse>('/bff/baskets', {
      baseUrl: config.BFF_BASE_URL,
      credentials: 'include',
    });
  } catch (error) {
    if (error instanceof HttpError && error.status === 404) {
      return { items: [], total: 0, updatedAt: new Date().toISOString() };
    }
    throw error;
  }
}

export async function saveBasket(items: BasketItem[]): Promise<BasketResponse> {
  if (!config.BFF_BASE_URL) {
    throw new Error('BFF base url is not configured');
  }

  return putJson<BasketResponse>('/bff/baskets', { items }, { baseUrl: config.BFF_BASE_URL, credentials: 'include' });
}
